﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace AutoUpdater
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args) {


            if (args == null || args.Length != 2) {
                return;
            }
            var version = args[0];
            var externalApp = args[1];

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (!VersionInspector.RequireUpdate(version)) {
                MessageBox.Show(Resource.GetString("Program.MessageBox.New"));
                return;
            }

            var message = string.Format(Resource.GetString("Program.MessageBox.Text"), VersionInspector.PackageInfo.Version, version);
            var result = MessageBox.Show(message, Resource.GetString("Program.MessageBox.Title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result != DialogResult.OK) {
                return;
            }

            Jermaine.UI.UnhandledExceptionHandler.Listen(AppDomain.CurrentDomain);
            Jermaine.UI.UnhandledExceptionHandler.HandlingException += HandlingException;
            Application.Run(new UpdatingForm(VersionInspector.PackageInfo, externalApp));
        }

        private static void HandlingException(object sender, Jermaine.UI.ExceptionHandlingEventArgs e) {
            var message = e.Message;
            Jermaine.Log.Default.Error(message);
            OnException();
        }


        private static void OnException() {
            var title = Resource.GetString("Program.MessageBox.ErrorTitle");
            var text = Resource.GetString("Program.MessageBox.ErrorText");
            MessageBox.Show(text, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            Environment.Exit(0);
        }
    }
}
